package severlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import dao.PassageMapper;
import model.Passage;
import util.SqlSessionUtil;

/**
 * Servlet implementation class SreachServlet
 */
@WebServlet("/SearchServlet")
/**
* @author 听风寂  ，林舒馨
* @date 2020/1/8
* @ClassName SearchServlet
*/
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
				//获取JSON的数据
				String search = request.getParameter("search");		
				String reading = request.getParameter("reading");
				request.getSession().setAttribute("reading", reading);
				//User user = (User) request.getSession().getAttribute("user");
				//解决后端向前端传数据中文乱码问题
				 response.setCharacterEncoding("UTF-8");
				SqlSession s=SqlSessionUtil.getSqlSession();
				PassageMapper up = s.getMapper(PassageMapper.class);
				List<Passage> findList = up.keySelect(search);
				JSONObject object=new JSONObject();
				PrintWriter out = response.getWriter();
				int flag=findList.size();
				if(flag<=0) {
					//查找不到相关文章
					object.put("code","0");
				}
				else{
					//查找到相关文章
					System.out.println(flag);
					object.put("code","1");
					object.put("passage",findList);
					}
				String jsonStr = JSON.toJSONString(object);
				out.print(jsonStr);
				out.close();	
				System.out.println(search);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
